package com.ruoyi.file.controller;

import com.ruoyi.common.core.utils.StringUtils;
import com.ruoyi.file.domain.PFileInfo;
import com.ruoyi.file.service.impl.PFileInfoServiceImpl;
import com.ruoyi.file.utils.VideoUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.utils.file.FileUtils;
import com.ruoyi.file.service.ISysFileService;
import com.ruoyi.system.api.domain.SysFile;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.List;

/**
 * 文件请求处理
 * 
 * @author ruoyi
 */
@CrossOrigin(origins = "http://localhost",allowCredentials = "true")
@RestController
public class SysFileController
{
    private static final Logger log = LoggerFactory.getLogger(SysFileController.class);

    @Autowired
    private ISysFileService sysFileService;
    @Autowired
    private PFileInfoServiceImpl fileInfoService;
    /**
     * 文件上传请求
     */
    @PostMapping("upload")
    public R<SysFile> upload(MultipartFile file, String remark,  String contactTable)
    {
        try
        {
            log.info("文件服务上传进来了:{}",file.getOriginalFilename());
            SysFile sysFile = new SysFile();
            String fileMd5 = getMd5(file);

            PFileInfo fileInfo = new PFileInfo();
            fileInfo.setFileMd5(fileMd5);
            List<PFileInfo> pFileInfos = fileInfoService.selectPFileInfoList(fileInfo);
            if(!pFileInfos.isEmpty()){
                fileInfo = pFileInfos.get(0);
                sysFile.setName(fileInfo.getFileName());
                sysFile.setUrl(fileInfo.getFileUrl());
                sysFile.setFileId(fileInfo.getId());
//                sysFile.setFileId(fileInfo.getId());
                return R.ok(sysFile);
            }
            // 上传并返回访问地址
            String url = sysFileService.uploadFile(file);

            sysFile.setName(FileUtils.getName(url));
            sysFile.setUrl(url);
            //保存图片到数据库
            fileInfo.setFileUrl(url);
            fileInfo.setFileName(FileUtils.getName(url));
            if(StringUtils.isEmpty(remark)){
                remark = "微信上传文件";
            }
            if(StringUtils.isEmpty(contactTable)){
                contactTable = "p_order";
            }
            fileInfo.setFileRemark(remark);
            fileInfo.setContactTable(contactTable);
            fileInfo.setFileSize(file.getSize()+"");
            fileInfo.setFileType(file.getOriginalFilename().substring(file.getOriginalFilename().indexOf(".")+1));
            fileInfoService.insertPFileInfo(fileInfo);
            sysFile.setFileId(fileInfo.getId());
//            sysFile.setFileId(fileInfo.getId());
            return R.ok(sysFile);
        }
        catch (Exception e)
        {
            log.error("上传文件失败", e);
            return R.fail(e.getMessage());
        }
    }

    /**
     * 获取上传文件的md5
     * @param file
     * @return
     * @throws
     */
    public String getMd5(MultipartFile file) throws IOException, NoSuchAlgorithmException {
        try {
            //获取文件的byte信息
            byte[] uploadBytes = file.getBytes();
            // 拿到一个MD5转换器
            MessageDigest md5 = MessageDigest.getInstance("MD5");
            byte[] digest = md5.digest(uploadBytes);
            //转换为16进制
            return new BigInteger(1, digest).toString(16);
        } catch (Exception e) {
            log.error(e.getMessage());
            throw e;
        }
    }

//    public void getPreViewUrl(File videoFile) {
//        String inputVideo = "path_to_your_video_file.mp4";
//        String outputImage = "path_to_output_image_file.jpg";
//
//        String cmd = "ffmpeg -i " + inputVideo + " -ss 00:00:01.000 -vframes 1 " + outputImage;
//
//        try {
//            Process process = Runtime.getRuntime().exec(cmd);
//            process.waitFor();
//            System.out.println("预览图生成成功：" + outputImage);
//        } catch (IOException | InterruptedException e) {
//            e.printStackTrace();
//        }
//        return null;
//    }
    /**
     * 文件上传请求
     */
    @GetMapping("upload2")
    public void upload(HttpServletResponse httpServletResponse)
    {
        try
        {
            File file1 = new File("C:\\Users\\lenovo\\Pictures\\1.mp4");
            VideoUtils.previewVideo(file1,httpServletResponse);
        }
        catch (Exception e)
        {

        }
    }

}